//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Lesser General Public License for more details.
// 
// You should have received a copy of the GNU Lesser General Public License
// along with this program.  If not, see http://www.gnu.org/licenses/.
// 

#include "Source.h"

namespace generator {

Define_Module(Source);

Source::Source():
		tickCount(1)
{
}

Source::~Source()
{
    cancelAndDelete(timerMessage);
}

void Source::initialize()
{
	markov = new Markov( par("pktMin"), par("pktMax") );
    timerMessage = new cMessage("timer");
    scheduleAt(simTime(), timerMessage);
}

void Source::generateOnOff(Pakiet* pakiet, int dest)
{
    if (uniform(0,1) >= 0.5)
    {
        send(pakiet, "out", dest);
    }
    scheduleAt(simTime()+1, timerMessage);
}

void Source::generateDefault(Pakiet* pakiet, int dest)
{
    send(pakiet, "out", dest);
    scheduleAt(simTime()+par("sendInterval").doubleValue(), timerMessage);
}

void Source::generateMarkov(Pakiet* pakiet, int dest)
{
    send(pakiet, "out", dest);
    double delay = markov->getDelay(tickCount);
    scheduleAt(simTime() + 1 + delay, timerMessage);
    markov->step(tickCount);
}


void Source::handleMessage(cMessage *msg)
{
    ASSERT(msg==timerMessage);
    //int dest = intuniform(0, gateSize("out")-1);
    int dest = 0;

    Pakiet *pakiet = new Pakiet("mojPakiet");
    pakiet->setSrc(getIndex());
    pakiet->setSessionId(5);
    pakiet->setPacketId(4);
    pakiet->setPriority(20);
    pakiet->setDst(dest);

    const char* gen = par("generation").stringValue();

    if (strcmp(gen, "onoff") == 0) {
    	generateOnOff(pakiet, dest);
    } else if (strcmp(gen, "mmpp") == 0) {
    	generateMarkov(pakiet, dest);
    } else {
    	generateDefault(pakiet, dest);
    }
    tickCount++;
}

}; // namespace
